<template>
  <el-dialog
      v-model="visible"
      title="分配组织"
      width="600px"
      :close-on-click-modal="false"
  >
    <el-tree
        ref="menuTreeRef"
        :data="menuTree"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="checkedKeys"
        :props="defaultProps"
        highlight-current
        check-strictly
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref,nextTick } from 'vue'
import type { ElTree } from 'element-plus'
import { tableInfoApi } from '@/api/core'
import type { Result, TreeNode } from '@/types/api'
import {orgApi} from "@/api/org";

// 是否显示弹窗
const visible = ref(false)

// 菜单树
const menuTree = ref<TreeNode<any>[]>([])

// 当前角色已有菜单ID
const checkedKeys = ref<string[]>([])

const menuTreeRef = ref<InstanceType<typeof ElTree>>()

const defaultProps = {
  children: 'children',
  label: 'label'
}

let currentRoleId: number

// 父组件回调事件
const emit = defineEmits(['submit'])

/**
 * 打开弹窗
 * @param roleId 角色ID
 */
async function openDialog(roleId: number) {
  currentRoleId = roleId
  visible.value = true

  // 1. 获取完整菜单树
  const resTree: Result<TreeNode<any>[]> = await tableInfoApi.tree('app_org')
  menuTree.value = resTree.data ?? []

  // 2. 获取角色已有菜单
  const resRole: Result<number[]> = await orgApi.haveTreeByRole(roleId)
  checkedKeys.value = (resRole.data ?? []).map(id => id.toString())

  // 等待 el-tree 渲染完成再设置选中，防止 default-checked-keys 不生效
  await nextTick()
  menuTreeRef.value?.setCheckedKeys(checkedKeys.value)
}

/**
 * 保存选择
 */
async function handleSave() {
  const checked = (menuTreeRef.value?.getCheckedKeys() ?? []) as number[]
  const halfChecked = (menuTreeRef.value?.getHalfCheckedKeys() ?? []) as number[]
  const allSelected = [...checked, ...halfChecked]
  emit('submit', allSelected,currentRoleId)
  visible.value = false
}

defineExpose({ openDialog })
</script>